package com.dudu.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.access.TianYiUtil;
import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.ILogService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.ISmsService;
import com.dudu.service.impl.AccountExtendServiceImpl;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.CheckValidityServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.service.impl.SmsServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.EnumUtility;
import com.dudu.utils.PhoneUtils;

import core.CoreService;

/**
 * 百悟短信
 * 
 * @author gaoxs
 * 
 */
public class OpenSmsController extends CoreService implements IOpenSmsController {
    // 应用扩展信息相关
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    // 账号
    private IAccountExtendService accountExtendService = new AccountExtendServiceImpl();
    // 验证信息类
    private ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
    // 运营平台相关操作
    private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();
    // 用于记录相应接口调用的日志
    private ILogService logService = new LogService();
    // 短信相关
    private ISmsService smsService = new SmsServiceImpl();

    @Override
    public String postSms() {
	log.info("load postSms");
	long begin = Calendar.getInstance().getTimeInMillis();
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// 应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// 组织账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 手机号码
	String phones = this.getRequest().getParameter("called");
	String[] calledStr = { "called", phones, "600", "0", "str" };
	checkParamlist.add(calledStr);
	// 用户ID
	String userIdentify = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", userIdentify, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// ISV自定义的短信id
	String msg_id = this.getRequest().getParameter("msg_id");
	String[] msg_idStr = { "msg_id", msg_id, "50", "1", "str" };
	checkParamlist.add(msg_idStr);

	if (EnumUtility.isBlank(msg_id)) {
	    msg_id = "";
	}
	// 短信模板编号
	String template_code = this.getRequest().getParameter("template_code");
	String[] template_codeStr = { "template_code", template_code, "30", "0", "str" };
	checkParamlist.add(template_codeStr);
	String temp = this.getRequest().getParameter("template_params");
	String[] template_paramsStr = { "template_params", temp, "500", "0", "str" };
	checkParamlist.add(template_paramsStr);
	// 是否需要上行，需要上行时随机使用扩展号(up_sms：1 需要上行)
	String up_sms = this.getRequest().getParameter("up_sms");
	if (StringUtils.isBlank(up_sms)) {
	    up_sms = "";
	}

	JSONObject object = null;
	String remoteAddr = this.getRemoteAddr();
	try {

	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		// 判断手机号码是否重复、是否正确、过滤外国号码等
		phones = PhoneUtils.phoneNumDereplication(phones);
		object = new JSONObject();
		if (phones.split(",").length <= 100) {
		    if (PhoneUtils.filterIssueNumber(phones)) {
			// 查询应用信息
			AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
			// 判断app信息是否为空
			if (appExtendBean != null) {
			    // 根据cust_account查询账号信息
			    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			    // 判断账号信息是否找到
			    if (accountBean != null) {
				// 验证秘钥信息
				if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				    // 判断账户余额验证
				    if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, AbilityTypeEnum.SMMS.getKey())) {
					if (EnumUtility.isBlank(temp)) {
					    object.put("result", "-1");
					    object.put("describe", "短信模板参数错误");
					    object.put("code", "0205");
					} else {
					    // 短信模板参数（String数组）
					    JSONArray template_params = JSONArray.fromObject(temp);
					    // 用于发送短信用service
					    object = smsService.postSms(accountBean, appExtendBean, userIdentify, phones, template_code, template_params, msg_id, remoteAddr,
						    up_sms, null);
					}

				    } else {
					object.put("result", "-1");
					object.put("code", "0009");
				    }
				} else {
				    object.put("result", "-1");
				    object.put("describe", "参数sign错误");
				    object.put("code", "0001");
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "未找到相应账号信息！");
				object.put("code", "0100");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "请使用正确的应用标识");
			    object.put("code", "0007");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的手机号码");
			object.put("code", "0100");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "每次提交的手机号码数量不能超过100个");
		    object.put("code", "0100");
		}
	    }

	} catch (Exception e) {
	    log.info("********发起短信失败**********");
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "错误");
	}
	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "ext_terminalCode:" + userIdentify + "|app_key:" + app_key + "|cust_account:" + cust_account + "|phones:" + phones + "|template_code:" + template_code
		+ "|template_params:" + temp + "|timestamp:" + timestamp + "|sign:" + sign + "|msg_id:" + msg_id + "|up_sms:" + up_sms;
	this.logService.logInterface(during, "sms", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), remoteAddr, phones);

	return returnData(object.toString());
    }

    /**
     * 自定义签名短信
     */
    @Override
    public String postSmsFreeSignature() {
	log.info("load postSms");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 应用标识
	String app_key = this.getRequest().getParameter("app_key");
	// 组织账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	// 手机号码
	String phones = this.getRequest().getParameter("called");
	// ISV自定义的短信id
	String msg_id = this.getRequest().getParameter("msg_id");
	if (EnumUtility.isBlank(msg_id)) {
	    msg_id = "";
	}
	// 短信模板编号
	String template_code = this.getRequest().getParameter("template_code");
	String temp = this.getRequest().getParameter("template_params");
	//自定义签名
	String sms_signature = this.getRequest().getParameter("sms_signature");
	if (EnumUtility.isBlank(sms_signature)) {
		sms_signature = "";
	}
	// 下发号码编码
	String sms_code = this.getRequest().getParameter("sms_code");
	if (EnumUtility.isBlank(sms_code)) {
		sms_code = "";
	}
	// 是否需要上行，需要上行时随机使用扩展号(up_sms：1 需要上行)
	String up_sms = this.getRequest().getParameter("up_sms");
	if (StringUtils.isBlank(up_sms)) {
	    up_sms = "";
	}
	// 用户ID
	String userIdentify = this.getRequest().getParameter("ext_terminalCode");

	JSONObject object = new JSONObject();
	String remoteAddr = this.getRemoteAddr();
	try {
	    // 判断手机号码是否重复、是否正确、过滤外国号码等
	    phones = PhoneUtils.phoneNumDereplication(phones);
	    if (phones.split(",").length <= 100) {
		if (PhoneUtils.filterIssueNumber(phones)) {
		    // 查询应用信息
		    AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		    // 判断app信息是否为空
		    if (appExtendBean != null) {
			// 根据cust_account查询账号信息
			AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			// 判断账号信息是否找到
			if (accountBean != null) {
			    // 验证秘钥信息
			    if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				// 判断账户余额验证
				if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, AbilityTypeEnum.SMMS.getKey())) {
				    if (EnumUtility.isBlank(temp)) {
					object.put("result", "-1");
					object.put("describe", "短信模板参数错误");
					object.put("code", "0205");
				    } else {
					// 短信模板参数（String数组）
					JSONArray template_params = JSONArray.fromObject(temp);
					// 用于发送短信用service
					object = smsService.postSms(accountBean, appExtendBean, userIdentify, phones, template_code, template_params, msg_id, remoteAddr, up_sms, sms_signature);
				    }

				} else {
				    object.put("result", "-1");
				    object.put("code", "0009");
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "参数sign错误");
				object.put("code", "0001");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "未找到相应账号信息！");
			    object.put("code", "0100");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的应用标识");
			object.put("code", "0007");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的手机号码");
		    object.put("code", "0100");
		}
	    } else {
		object.put("result", "-1");
		object.put("describe", "每次提交的手机号码数量不能超过100个");
		object.put("code", "0100");
	    }
	} catch (Exception e) {
	    log.info("********发起短信失败**********");
	    object.put("result", "-1");
	    object.put("describe", "错误");
	}
	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "ext_terminalCode:" + userIdentify + "|app_key:" + app_key + "|cust_account:" + cust_account + "|phones:" + phones + "|template_code:" + template_code
		+ "|template_params:" + temp + "|timestamp:" + timestamp + "|sign:" + sign + "|msg_id:" + msg_id+"|up_sms:"+up_sms+"|sms_signature:"+sms_signature;
	this.logService.logInterface(during, "smsFreeSignature", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), remoteAddr, phones);

	return returnData(object.toString());
    }
    
    @Override
    public String QuickSms() {
	String phone = this.getRequest().getParameter("phone");
	TianYiUtil.QuickSMS(phone);
	JSONObject object = new JSONObject();
	object.put("result", "success");
	return returnData(object.toString());
    }
}
